package org.znxs.znmanus.rag.c_embedding;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.milvus.MilvusVectorStore;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.znxs.znmanus.rag.a_etl.MarkDownLoader;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

// 使用 sdk 引入 milvus向量数据库
//@Configuration
//public class MilvusConfig {
//
//    private final MilvusClientV2 milvusClient;
//
//
//    public MilvusConfig() {
//        this.milvusClient = new MilvusClientV2(ConnectConfig.builder()
//                .uri("http://192.168.239.128:19530")
//                .build());
//    }
//
//
//}

@Configuration
@Slf4j
public class MilvusVectorVectorDataInit implements ApplicationRunner {

    private final MilvusVectorStore vectorStore;

    public MilvusVectorVectorDataInit(MilvusVectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }

    @Resource
    private MarkDownLoader markDownLoader;

    // 标志位，确保只执行一次
    private final AtomicBoolean hasRun = new AtomicBoolean(false);


    @Override
    public void run(ApplicationArguments args) {

        if (hasRun.get()) {
            log.warn("MilvusVectorVectorDataInit 已执行过，跳过重复执行");
            return;
        }

        List<Document> documents = markDownLoader.loadMarkDowns("classpath:doc/*.md");
        int batchSize = 25;
        for (int i = 0; i < documents.size(); i += batchSize) {
            int end = Math.min(i + batchSize, documents.size());
            List<Document> batch = documents.subList(i, end);
            vectorStore.add(batch);
            log.info("Added document batch starting at {}", i);
        }
        log.info("Vector data ");
        hasRun.set(true); // 设置为已执行
    }
}
